#include<iostream>
#include<unistd.h>
#include<fcntl.h>
#include<cstring>
using namespace std;



void SetNoBlock(int fd)
{
    int fl = fcntl(fd, F_GETFL);
    if (fl < 0)
    {
        perror("fcntl");
        exit(0);
    }
    fcntl(fd, F_SETFL, fl | O_NONBLOCK);
}


int main()
{
    SetNoBlock(0);
    char buffer[1024];
    while (true)
    {
        cout << "Please Enter# ";
        fflush(stdout); 

        ssize_t n = read(0, buffer, sizeof(buffer) - 1);
        if (n > 0)
        {
            buffer[n - 1] = 0;
            cout << "echo: " << buffer << endl;
        }
        else if (n == 0)
        {
            cout << "read done" << endl;
        }
        else
        {
            if (errno == EWOULDBLOCK)
            {
                cout << "not ready, try again" << endl;
                sleep(1);
        
            }
            else
            {

                cout << "read error n = "  << n << endl;
                cout << "error code: " << errno << " " << "strerror: " << strerror(errno) << endl;
            
            }
        }

    }
    return 0;
}